package crontab

import (
	"dataconvertserver/server/appcore"
	"dataconvertserver/server/configclass"
	"dataconvertserver/utils"
	"dataconvertserver/utils/ormdb"
	"time"

	"gitlab.upchinaproduct.com/taf/tafgo/taf"

	"github.com/robfig/cron"
)

var loggerObj = taf.GetDayLogger("Crontab", 1)

func Init() {

	oneTask := cron.New()

	for databaseId, databaseConfig := range configclass.GetConfigManager().GetAllConfigs() {
		loggerObj.Debugf("{databaseConfig}|%+v", databaseConfig)

		sourceDb, _ := ormdb.GetSourceDb(databaseId)
		destinationDb, _ := ormdb.GetDestinationDb(databaseId)
		if sourceDb == nil || destinationDb == nil {
			loggerObj.Errorf("{initErr sourceDb^destinationDb}|%+v|%+v", sourceDb, destinationDb)
			continue
		}

		if databaseConfig.Status == "1" {
			cronStr := databaseConfig.Crontab
			if databaseConfig.Source.IncrementDatetime == "now" {
				configclass.GetConfigManager().SetIncrementDatetime(databaseId, utils.TimeToDefaultStr(time.Now()))
			}
			loggerObj.Debugf("{databaseConfig.Source.IncrementDatetime}|%+v", databaseConfig.Source.IncrementDatetime)
			err := oneTask.AddFunc(cronStr, func() {
				// ConvertSourceToDestination(loggerObj, sourceDb, &databaseConfig.Source, destinationDb, &databaseConfig.Destination)
				var retSrc, errHandleSource = appcore.HandleSourceDatabase(loggerObj, databaseId, "")
				if retSrc != 0 || errHandleSource != nil {
					loggerObj.Debugf("{warning HandleSourceDatabase databaseId^ret^error}|%s|%d|%+v", databaseId, retSrc, errHandleSource)
				} else {
					loggerObj.Debugf("{success HandleSourceDatabase databaseId^ret^error}|%s|%d|%+v", databaseId, retSrc, errHandleSource)
				}
			})
			if err != nil {
				loggerObj.Debugf("{warning installCron}|%s", cronStr)
				continue
			}
		}
	}
	oneTask.Start()
	appcore.Init()
}
